package com.okaixz.client.controller;

import cn.hutool.core.util.XmlUtil;
import com.okaixz.client.model.dto.UserDto;
import com.okaixz.client.model.dto.WxMessage;
import com.okaixz.client.service.IWxService;
import com.okaixz.common.annotation.Anonymous;
import com.okaixz.common.annotation.OpLog;
import com.okaixz.common.client.Result;
import com.okaixz.common.client.WsResult;
import com.okaixz.common.client.vo.WxAppPayParams;
import com.okaixz.common.constant.CommonConstants;
import com.okaixz.common.constant.OpConstants;
import com.okaixz.common.constant.WsResultCode;
import com.okaixz.common.core.controller.BaseController;
import com.okaixz.manager.utils.WxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 二级菜单管理Controller
 *
 * @author ruoyi
 * @date 2024-08-17
 */
@RestController
@RequestMapping("/wx")
@Anonymous
@Slf4j
public class WxController extends BaseController {
    private String token = "abcd1234";
    @Autowired
    private IWxService wxService;

    @Autowired
    private WxPayUtil wxPayUtil;

    /**
     * 微信签名验证
     */
    @GetMapping("/check")
    public String list(@RequestParam(value = "signature") String signature
            , @RequestParam String timestamp
            , @RequestParam String nonce
            , @RequestParam String echostr
    ) {
        return echostr;
    }

    /**
     * 微信公众号消息
     */
    @PostMapping("/check")
    public String onMessage(HttpServletRequest request) throws Exception {
        ServletInputStream inputStream = request.getInputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(buf)) != -1) {
            String s = new String(buf, 0, len);
            sb.append(s);
        }
        String xmlStr = sb.toString();
        log.info("收到微信公众号消息:{}", xmlStr);
        Document document = XmlUtil.parseXml(xmlStr);
        WxMessage wxMessage = XmlUtil.xmlToBean(document.getFirstChild(), WxMessage.class);
        log.info("收到微信公众号消息:{}", wxMessage);

        wxService.onMessage(wxMessage);

        return "";
    }

    /**
     * 获取登录扫描二维码
     */
    @GetMapping("/qrcode")
    public Result<String> list(String sid) {
        return Result.success(wxService.getQrcode(sid));
    }

    /**
     * 微信扫描二维码登录后的回调接口
     */
    @GetMapping("/loginCallBack")
    public String wxLoginCallBack(String code, String state) {
        UserDto wxUserInfo = wxService.processWxQrcodeLoginCallBack(code, state);
        if (wxUserInfo == null) {
            WebSocketServer.sendData(state, WsResult.success(wxUserInfo, WsResultCode.LOGIN_FAIL));
        } else {
            WebSocketServer.sendData(state, WsResult.success(wxUserInfo, WsResultCode.LOGIN_SUCCESS));
        }
        return "http://weixin.qq.com/r/mp/yhHWzn3EYiAdrTmt90TY";
    }

    /**
     * 微信扫描二维码支付后的回调接口  小程序支付后的回调接口
     */
    @PostMapping("/native_pay_callback")
    public String nativePayCallback(HttpServletRequest request, HttpServletResponse response) {

        String result = wxService.processNativePayCallback(request, response);

        return result;
    }
    /**
     * 微信app支付后的回调接口
     */
    @PostMapping("/app_pay_callback")
    @OpLog(opType = "", opDesc = OpConstants.WX_APP_PAY_CALLBACK,isSaveResponseData =true)
    public String appPayCallback(HttpServletRequest request, HttpServletResponse response) {
        String result = wxService.processAppPayCallback(request, response);
        return result;
    }

    /**
     * 获取带参二维码
     */
    @GetMapping("/token")
    public String getToken() {
        String result = wxService.getQrcodeWithParams("666", CommonConstants.WX_QRCODE_TYPE_LOGIN);
        return result;
    }

    /**
     * 微信小程序登录
     */
    @GetMapping(value = {"/login/{code}/{shareUserId}", "/login/{code}"})
    public Result<UserDto> wxMiniprogramLogin(@PathVariable(name = "code", required = true) String code, @PathVariable(name = "shareUserId", required = false) String shareUserId) {
        UserDto userDto = wxService.wxMiniprogramLogin(code, shareUserId);
        return Result.success(userDto);
    }

    /**
     * 微信小程序支付测试
     */
    @GetMapping("/pay/{code}")
    public Result<String> testMiniprogramPay(@PathVariable(name = "code") String code) {
        String result = "";
        try {
//            result = wxPayUtil.createOrder();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(result);
    }
    /**
     * 微信app支付预付接口
     */
    @PostMapping("/pay/app")
    @OpLog(opType = "", opDesc = OpConstants.WX_APP_PAY_PRE_PAY,isSaveResponseData =true)
    public Result<WxAppPayParams> getWxAppPayParams(String userId, Integer gid) {
        WxAppPayParams wxAppPayParams = wxService.wxAppCreateOrder(userId, gid, null);
        return Result.success(wxAppPayParams);
    }


}
